<template>
  <el-card class="box-card" shadow="hover">
    <el-button
      type="primary"
      :icon="Plus"
      @click="showDialog({ id: 0, tmName: '', logoUrl: '' })"
      >添加</el-button
    >
    <el-table
      :data="trademarkList"
      border
      style="width: 100%"
      class="marginTop"
      v-loading="loading"
    >
      <el-table-column label="序号" width="60" type="index" align="center" />
      <el-table-column prop="tmName" label="品牌名称" />
      <el-table-column label="品牌LOGO">
        <!-- <img src="logoUrl" /> -->
        <template v-slot="{ row }">
          <el-image :src="row.logoUrl" fit="fill" lazy class="trademark-logo">
            <!-- 具名插槽：当图片加载失败时显示的内容 -->
            <template #error>
              <div class="image-slot">
                <el-icon><icon-picture /></el-icon>
              </div>
            </template>
          </el-image>
        </template>
      </el-table-column>

      <el-table-column label="操作">
        <template v-slot="{ row }">
          <el-button
            type="warning"
            size="small"
            :icon="Edit"
            @click="showDialog(row)"
          ></el-button>
          <el-button
            type="danger"
            size="small"
            :icon="Delete"
            @click="deleteTrademark(row)"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      class="marginTop"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      :page-sizes="[3, 6, 9, 12]"
      layout="prev, pager, next, jumper, ->, sizes, total"
      :total="total"
      @size-change="getTrademarkList"
      @current-change="getTrademarkList"
    />

    <el-dialog
      v-model="dialogVisible"
      :title="trademarkFormData.id ? '修改品牌' : '添加品牌'"
      width="40%"
    >
      <el-form
        label-width="90px"
        :model="trademarkFormData"
        :rules="trademarkFormRules"
        ref="trademarkRef"
      >
        <el-form-item label="品牌名称" prop="tmName">
          <el-input
            class="trademark-input"
            placeholder="请输入品牌名称"
            v-model="trademarkFormData.tmName"
          />
        </el-form-item>
        <el-form-item label="品牌LOGO" prop="logoUrl">
          <!-- 
            action 上传图片的地址
              action="/admin/product/fileUpload" 不行，没有服务器地址
              action="http://gmall-h5-api.atguigu.cn/admin/product/fileUpload" 不行，跨域
              action="/app-dev/admin/product/fileUpload" 不行，本地开发可以，上线不行（上线请求前缀变了，变成/app-prod）
              请求前缀需要从 import.meta.env.VITE_API_URL 获取
           -->
          <el-upload
            class="avatar-uploader"
            :action="BASE_Url + '/admin/product/upload'"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload"
          >
            <img
              v-if="trademarkFormData.logoUrl"
              :src="trademarkFormData.logoUrl"
              class="avatar"
            />
            <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            <template #tip>
              <div class="el-upload__tip">
                只能上传jpg/png文件，且不超过200kb
              </div>
            </template>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelTrademark">取消</el-button>
          <el-button type="primary" @click="addOrUpdateTrademark">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>
  </el-card>
</template>
<script lang="ts">
export default {
  name: "CTrademark",
};
</script>

<script lang="ts" setup>
import { onMounted, reactive, ref } from "vue";
import {
  getTrademarkListApi,
  addTrademarkApi,
  updateTrademarkApi,
  deleteTrademarkApi,
} from "@/api/product/trademark";
import type {
  TrademarkList,
  TrademarkItem,
} from "@/api/product/model/trademarkModel";
import {
  Plus,
  Edit,
  Delete,
  Picture as IconPicture,
} from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { UploadProps } from "element-plus";
import { beforeAvatarUpload } from "@/utils/tools";

/*********************** 删除功能及表单校验 *********************************/

const deleteTrademark = (row: TrademarkItem) => {
  const { id, tmName } = row;
  ElMessageBox.confirm(`确定要删除 ${tmName} 嘛？`, "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      await deleteTrademarkApi(id);
      ElMessage.success("删除品牌成功");
      // 删除完成后应该刷新页面
      getTrademarkList();
    })
    .catch(() => {
      ElMessage({});
    });
};

/*********************** 添加和修改功能及表单校验 *********************************/
// 点击确定按钮
const addOrUpdateTrademark = async () => {
  // 1.校验整个表单
  await trademarkRef.value.validate();
  // 2.校验通过，发送请求，校验不通过走不到这里来
  const { id, tmName, logoUrl } = trademarkFormData;
  if (id) {
    await updateTrademarkApi(trademarkFormData);
    // 修改品牌成功响应用户
    ElMessage.success("修改品牌成功");
  } else {
    await addTrademarkApi(tmName, logoUrl);
    // 添加品牌成功响应用户
    ElMessage.success("添加品牌成功");
  }
  // 添加或修改成功后关闭对话框
  dialogVisible.value = false;
  // 添加完成后应该刷新页面
  getTrademarkList();
};

// 点击取消按钮
const cancelTrademark = () => {
  // trademarkFormData.tmName = "";
  // trademarkFormData.logoUrl = "";
  // trademarkFormData.id = 0;
  // 添加成功后关闭对话框
  dialogVisible.value = false;
};

// 定义表单数据
const trademarkFormData = reactive({
  // 参数名来源于接口文档
  // 品牌名称
  tmName: "",
  // 品牌LOGO
  logoUrl: "",
  id: 0,
});

// 定义表单校验规则
const trademarkFormRules = reactive({
  // 表单校验规则名称必须和数据名称一致
  tmName: [
    {
      required: true, //必填项
      message: "请输入品牌名称", //错误提示信息
      trigger: "blur", //触发表单校验时机，失去焦点
    },
    {
      min: 2,
      max: 10,
      message: "名称只允许2-10位",
      trigger: "blur",
    },
  ],
  logoUrl: [
    {
      required: true,
      message: "请上传图片LOGO",
    },
  ],
});
// 获取el-form组件实例对象，以便后面使用它身上的方法
const trademarkRef = ref();

/*********************** 图片上传功能 *********************************/
// 配置请求前缀
const BASE_Url = import.meta.env.VITE_API_URL;
// 定义一个响应式的图片地址，后面给它赋值
// const imageUrl = ref("");

// 图片上传成功执行的回调
const handleAvatarSuccess: UploadProps["onSuccess"] = (response) => {
  trademarkFormData.logoUrl = response.data;
  // 清空表单校验失败信息
  // trademarkFormRef.value.clearValidate(); // 清空所有表单项的校验信息
};

// 图片上传之前执行的回调,在这里做一些图片的限制
// 函数封装成一个工具函数了  直接引入使用 import { beforeAvatarUpload } from "@/utils/tools";
/* const beforeAvatarUpload: UploadProps["beforeUpload"] = (rawFile) => {
  // rawFile 上传图片文件
  //  type 图片类型
  //   size 图片大小

  //  定义一个合法图片的数组
  const validImageType = ["image/jpeg", "image/png"];
  if (!validImageType.includes(rawFile.type)) {
    ElMessage.error("图片的格式只能是jpeg或者png!!!");
    return false;
  } else if (rawFile.size > 200 * 1024) {
    ElMessage.error("图片的大小不能超过200kb!!!");
    return false;
  }
  return true;
}; */

/*********************** 分类管理相关 *********************************/
// 当前页码
const currentPage = ref<number>(1);
// 每页条数
const pageSize = ref<number>(5);
// 总页数
const total = ref<number>(0);
// 定义品牌列表数据
const trademarkList = ref<TrademarkList>([]);
// 定义loading效果
const loading = ref(false);

// 封装公共请求函数
const getTrademarkList = async () => {
  loading.value = true;
  const res = await getTrademarkListApi(currentPage.value, pageSize.value);
  // console.log(res);
  total.value = res.total;
  trademarkList.value = res.records;
  loading.value = false;
};

onMounted(getTrademarkList);

/*********************** 添加或修改后显示及隐藏对话框 *********************************/
// 定义对话默认值
const dialogVisible = ref(false);

// // 点击添加按钮执行的回调
// const showAddDialog = () => {
//   trademarkFormData.tmName = "";
//   trademarkFormData.logoUrl = "";
//   trademarkFormData.id = 0;
//   dialogVisible.value = true;
//   trademarkRef.value.clearValidate(); //清空校验信息
// };

// // 点击修改按钮执行的回调
// const showUpdateDialog = async (row: TrademarkItem) => {
//   dialogVisible.value = true;
//   trademarkFormData.id = row.id;
//   trademarkFormData.tmName = row.tmName;
//   trademarkFormData.logoUrl = row.logoUrl;
//   trademarkRef.value.clearValidate(); //清空校验信息
// };

// 封装公共的回调
const showDialog = async (row: TrademarkItem) => {
  dialogVisible.value = true;
  trademarkFormData.id = row.id;
  trademarkFormData.tmName = row.tmName;
  trademarkFormData.logoUrl = row.logoUrl;
  // 加上可选链的目的是为防止在页面渲染第一次的时候trademarkRef.value的值是undefined，以为数据更新是同步的页面更新是异步的
  trademarkRef.value?.clearValidate(); //清空校验信息
};
</script>

<style scoped>
.marginTop {
  margin-top: 20px;
}
.trademark-logo {
  width: 100px;
  height: 80px;
}
.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  height: 100%;
  background: var(--el-fill-color-light);
  color: var(--el-text-color-secondary);
  font-size: 30px;
}
.dialog-footer button:first-child {
  margin-right: 10px;
}
.trademark-input {
  width: 500px;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
